import Vue from "vue";
import VueRouter from "vue-router";
import AdminLogin from "../views/admin/AdminLogin.vue";
import AdminUser from "../views/admin/AdminUser.vue";
import AdminHome from "../views/admin/AdminHome.vue";
import AdminHistory from "../views/admin/AdminHistory.vue";

import Home from "../views/user/Home.vue";
import UserLogin from "../views/user/UserLogin.vue";
import UserHome from "../views/user/UserHome.vue";
import DisHistory from "../views/user/DisHistory.vue";
import Single from "../views/user/Single.vue";
import Multiple from "../views/user/Multiple.vue";
import Hot from "../views/user/Hot.vue";
import HomeIndex from "../views/user/HomeIndex.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/login",
    component: UserLogin,
    children: [{ path: "login", component: UserLogin }],
  },
  {
    path: "/adminlogin",
    component: AdminLogin,
  },
  {
    path: "/admin",
    name: "Admin",
    component: AdminHome,
    redirect: "/users",
    children: [
      { path: "/users", component: AdminUser },
      { path: "/history", component: AdminHistory },
    ], // 管理员主页
  },
  {
    path: "/home",
    name: "Home",
    component: Home,
    redirect: "/home",
    children: [
      { path: "/home", component: HomeIndex },
      { path: "/single", component: Single },
      { path: "/Multiple", component: Multiple },
      { path: "/hot", component: Hot },
      { path: "/userHome", component: UserHome },
      { path: "/dishistory", component: DisHistory },
    ], // 用户主页
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 挂在路由守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行  next() 放行   next('/login') 强制跳转
  if (to.path === "/login") return next();
  if (to.path === "/adminlogin") return next();
  // 获取token
  const user = window.sessionStorage.getItem("user");
  if (!user) return next("/");
  next();
});

export default router;
